package com.zcily.demo.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitConfig {

    public static final String COMMON_QUEUE = "common.queue";
    public static final String COMMON_EXCHANGE = "common.exchange";
    public static final String COMMON_ROUTINGKEY = "common.routingkey";
    public static final String COMMON_LISTENER = "common.listener";

    @Bean("commonQueue")
    public Queue commonQueue() {
        return new Queue(COMMON_QUEUE, true, false, false);
    }

    @Bean("commonExchange")
    public DirectExchange commonExchange() {
        return new DirectExchange(COMMON_EXCHANGE, true, false);
    }

    @Bean("bindingCommonQueue")
    public Binding bindingCommonQueue(
            @Qualifier("commonQueue") Queue queue,
            @Qualifier("commonExchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(COMMON_ROUTINGKEY).noargs();
    }

    // *********************************************************************************************************************

    public static final String DELAYED_QUEUE = "delayed.queue";
    public static final String DELAYED_EXCHANGE = "delayed.exchange";
    public static final String DELAYED_ROUTINGKEY = "delayed.routingkey";

    @Bean("delayedExchange")
    public CustomExchange delayedExchange() {
        Map<String, Object> args = new HashMap<>();
        args.put("x-delayed-type", "direct"); // 指定交换器类型为direct，这是必需的配置项之一
        return new CustomExchange(DELAYED_EXCHANGE, "x-delayed-message", true, false, args);
    }

    @Bean("delayedQueue")
    public Queue delayedQueue() {
        return new Queue(DELAYED_QUEUE, true); // 持久化队列，确保消息不会丢失
    }

    @Bean("bindingDelayedQueue")
    public Binding bindingDelayedQueue(
            @Qualifier("delayedQueue") Queue queue,
            @Qualifier("delayedExchange") CustomExchange delayedExchange) {
        return BindingBuilder.bind(queue).to(delayedExchange).with(DELAYED_ROUTINGKEY).noargs();
    }
}
